package com.wanmait.spacesys.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.wanmait.spacesys.util.DbHelper;
import com.wanmait.spacesys.vo.UserQusetion;

public class ForgetDAO {
		//单一实例
	private ForgetDAO() {}
	private static ForgetDAO dao = new ForgetDAO();
	public static ForgetDAO getDAO() {
		return dao;
	}
	

	//判断数据库中是否有这个账号
	public boolean isName(String username) {
		String sql = "select * from userinfo where username=?";
		Connection conn = DbHelper.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, username);
			rs = ps.executeQuery();
			return rs.next();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			DbHelper.close(rs, ps, conn);
		}
		return false;
	}
	
	//查出数据库里所有的问题
	public List<UserQusetion> findAll(){
		String sql = "select * from userquestion";
		List<UserQusetion> userQusetions = new ArrayList<>();
		Connection conn = DbHelper.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				UserQusetion userQusetion  =new UserQusetion();
				userQusetion.setId(rs.getInt("id"));
				userQusetion.setAnswer(rs.getString("answer"));
				userQusetion.setQuestion(rs.getString("question"));
				
				userQusetions.add(userQusetion);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			DbHelper.close(rs, ps, conn);
			
		}
		return userQusetions;
	}
	
	//判断用户的答案是否正确
	public  UserQusetion isCorrect(Integer id,String answer) {
		UserQusetion userQusetion = null;
		
		String sql = "select * from userquestion where id=? and answer=?";
		Connection conn = DbHelper.getConnection();
		PreparedStatement ps= null;
		ResultSet rs = null;
		try {
			ps=conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.setString(2, answer);
			rs= ps.executeQuery();
			if(rs.next()) {
				userQusetion = new UserQusetion();
				userQusetion.setId(id);
				userQusetion.setAnswer(rs.getString("answer"));
				userQusetion.setQuestion(rs.getString("question"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			DbHelper.close(rs, ps, conn);
		}
		return userQusetion;
		
	}
}
